// 响应拦截器
import {
  Injectable,
  NestInterceptor,
  CallHandler,
  ExecutionContext,
} from '@nestjs/common';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { Logger } from '../utils/log4js';

interface data<T> {
  data: T;
}

@Injectable()
export class Response<T = any> implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<data<T>> {
    const req = context.getArgByIndex(1).req;
    return next.handle().pipe(
      map((data) => {
        const logFormat = 
` <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  Request original url: ${req.originalUrl}
  Method: ${req.method}
  IP: ${req.ip}
  User: ${req.user ? req.user.username : '未知'}
  Response data: ${JSON.stringify(data)}
  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
`;
        Logger.info(logFormat);
        Logger.access(logFormat);
        return {
          data,
          status: 200,
          success: true,
          message: '操作成功',
        };
      }),
    );
  }
}
